#include "Common/Utility/XmlUtility.h"
#include "base/core/com_define.h"
#include "base/core/char_operation.h"

bool GetXmlIntAttrib(XMLElement* element, const char* key, int default_value, int* ret_value) 
{
    bool result = false;
    XMLError errorId = XML_NO_ATTRIBUTE;

    MMOLOG_PROCESS_ERROR(element != nullptr);
    MMOLOG_PROCESS_ERROR(key != nullptr);

    errorId = element->QueryIntAttribute(key, ret_value);
    MMO_PROCESS_ERROR(errorId == XML_NO_ERROR);

    result = true;
Exit0:
    if (!result && ret_value)
        *ret_value = default_value;
    return result;
}

bool GetXmlBoolAttrib(XMLElement* element, const char* key, bool default_value, bool* ret_value) 
{
    bool result = false;
    XMLError errorId = XML_NO_ATTRIBUTE;

    MMOLOG_PROCESS_ERROR(element != nullptr);
    MMOLOG_PROCESS_ERROR(key != nullptr);

    errorId = element->QueryBoolAttribute(key, ret_value);
    MMO_PROCESS_ERROR(errorId == XML_NO_ERROR);

    result = true;
Exit0:
    if (!result && ret_value)
        *ret_value = default_value;
    return result;
}

bool GetXmlFloatAttrib(XMLElement* element, const char* key, float default_value, float* ret_value) 
{
    bool result = false;
    XMLError errorId = XML_NO_ATTRIBUTE;

    MMOLOG_PROCESS_ERROR(element != nullptr);
    MMOLOG_PROCESS_ERROR(key != nullptr);

    errorId = element->QueryFloatAttribute(key, ret_value);
    MMO_PROCESS_ERROR(errorId == XML_NO_ERROR);

    result = true;
Exit0:
    if (!result && ret_value)
        *ret_value = default_value;
    return result;
}

bool GetXmlDoubleAttrib(XMLElement* element, const char* key, double default_value, double* ret_value) 
{
    bool result = false;
    XMLError errorId = XML_NO_ATTRIBUTE;

    MMOLOG_PROCESS_ERROR(element != nullptr);
    MMOLOG_PROCESS_ERROR(key != nullptr);

    errorId = element->QueryDoubleAttribute(key, ret_value);
    MMO_PROCESS_ERROR(errorId == XML_NO_ERROR);

    result = true;
Exit0:
    if (!result && ret_value)
        *ret_value = default_value;
    return result;
}

bool GetXmlStrAttrib(XMLElement* element, const char* key, const char* default_str, char* ret_str, unsigned int buf_max_size) 
{
    bool result = false;
    bool retCode = false;
    const char* attrib = nullptr;

    MMOLOG_PROCESS_ERROR(element != nullptr);
    MMOLOG_PROCESS_ERROR(key != nullptr);
    MMOLOG_PROCESS_ERROR(ret_str != nullptr);

    attrib = element->Attribute(key);
    MMO_PROCESS_ERROR(attrib != nullptr);

    retCode = SafeCopyString(ret_str, buf_max_size, attrib);
    MMOLOG_PROCESS_ERROR(retCode);

    result = true;
Exit0:
    if (!result) 
	{
        if (ret_str && default_str)
            SafeCopyString(ret_str, buf_max_size, default_str);
    }
    return result;
}